package org.study.atomikos.jdbc.boot.config;

import com.atomikos.icatch.jta.UserTransactionImp;
import com.atomikos.icatch.jta.UserTransactionManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.jta.JtaTransactionManager;

import javax.sql.DataSource;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

/**
 * 注意：这里除了加载的配置不同之外，DataSource 也采用了 AtomikosDataSourceBean 注意与之前配置多数据源使用的配置和实现类的区别。
 *
 * @author Administrator
 * @date 2021-11-29
 */
@Configuration
@EnableTransactionManagement
public class DataSourceConfiguration {
    @Bean(name = "primaryDataSource")
    @DependsOn(value = {"transactionManager"})
    @ConfigurationProperties(prefix = "spring.atomikos.datasource.primary")
    public DataSource primaryDataSource() {
        AtomikosDataSourceBean atomikosDataSourceBean = new AtomikosDataSourceBean();
        return atomikosDataSourceBean;
    }

    @Bean(name = "primaryJdbcTemplate")
    public JdbcTemplate primaryJdbcTemplate(@Qualifier("primaryDataSource") DataSource primaryDataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(primaryDataSource);
        return jdbcTemplate;
    }

    @Bean(name = "secondaryDataSource")
    @DependsOn(value = {"transactionManager"})
    @ConfigurationProperties(prefix = "spring.atomikos.datasource.secondary")
    public DataSource secondaryDataSource() {
        AtomikosDataSourceBean atomikosDataSourceBean = new AtomikosDataSourceBean();
        return atomikosDataSourceBean;
    }

    @Bean(name = "secondaryJdbcTemplate")
    public JdbcTemplate secondaryJdbcTemplate(@Qualifier("secondaryDataSource") DataSource secondaryDataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(secondaryDataSource);
        return jdbcTemplate;
    }

    @Bean(name = "transactionManager")
    public JtaTransactionManager transactionManager() throws SystemException {
        UserTransaction userTransaction = new UserTransactionImp();
        userTransaction.setTransactionTimeout(30);
        UserTransactionManager userTransactionManager = new UserTransactionManager();
        userTransactionManager.setForceShutdown(false);
        JtaTransactionManager jtaTransactionManager = new JtaTransactionManager(userTransaction, userTransactionManager);
        return jtaTransactionManager;
    }
}
